package com.gszyxy.mallfour.merchant.merchant;


import com.gszyxy.mallfour.merchant.params.MerchantRequestParams;
import com.gszyxy.mallfour.merchant.pojo.Goods;
import com.gszyxy.mallfour.merchant.pojo.Merchant;
import com.gszyxy.mallfour.merchant.service.MerchantService;
import com.gszyxy.mallfour.utils.MD5;
import com.gszyxy.mallfour.utils.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("merchant")
public class MerchantHandler {
    @Resource
    private MerchantService merchantService;
    @RequestMapping("add")
    public R addMerchant(@RequestBody MerchantRequestParams merchant) {
        Merchant merchant_obj = merchantService.findMerchantByName(merchant.getMname());
        if (merchant_obj != null) {
            return R.fail("您注册的用户名已经存在");
        }
        merchant.setMpassword(MD5.getMD5Hash(merchant.getMpassword()));
        return merchantService.addMerchant(merchant) >0 ? R.ok("注册成功"):R.fail("注册失败");
    }
    @RequestMapping("login")
    public R login(@RequestBody MerchantRequestParams merchant, HttpServletRequest request) {
        merchant.setMpassword(MD5.getMD5Hash(merchant.getMpassword()));
        Merchant merchant_obj = merchantService.login(merchant);
        if (merchant_obj != null) {
            request.getSession().setAttribute("mname", merchant.getMname());
        }

        return merchant_obj != null ? R.ok("登录成功") :R.fail("账号或密码错误");
    }



    @RequestMapping("update")
    public R updateMerchant(@RequestBody Merchant merchant, HttpServletRequest request) {
        merchant.setMstatus(0); //商家刚把入驻资料提交完毕，默认就是已提交但未审核状态
        merchant.setMname(request.getSession().getAttribute("mname").toString());
        merchant.setUpdate_by(request.getSession().getAttribute("mname").toString());
        return merchantService.updateMerchant(merchant) > 0 ? R.ok("资料提交成功，请等待审核") : R.fail("资料提交失败，请重试");
    }

    @GetMapping("list")
    public R list() {
        return merchantService.list().size() > 0 ? R.ok(merchantService.list()) : R.fail("暂时无商家入驻");

    }

    @PostMapping("g")
    public R addGoods(@RequestBody Goods goods) {
        return merchantService.addGoods(goods) == 1 ? R.ok("添加成功") : R.fail("添加失败");
    }

}
